package com.gzs.zhdj.service.impl;

import com.gzs.zhdj.constant.MessageConstant;
import com.gzs.zhdj.constant.RoleConstant;
import com.gzs.zhdj.domain.entity.Organization;
import com.gzs.zhdj.domain.entity.PartyMember;
import com.gzs.zhdj.exception.AccountErrorException;
import com.gzs.zhdj.mapper.OrganizationMapper;
import com.gzs.zhdj.mapper.AdminMapper;
import com.gzs.zhdj.service.OrganizationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class OrganizationServiceImpl implements OrganizationService {
    @Autowired
    private OrganizationMapper organizationMapper;
    @Autowired
    private AdminMapper adminMapper;
    @Override
    public void createPartyOrg(Organization organization) {
        String name = organization.getLeader();
        PartyMember partyMember = adminMapper.getByName(name);
        if (partyMember == null) {
            throw new AccountErrorException(MessageConstant.NAME_ERROR);
        }
        adminMapper.updateRole(name, RoleConstant.ADMIN);
        organization.setPId(partyMember.getId());
        organizationMapper.insertPartyOrg(organization);
    }

    @Override
    public void updatePartyOrg(Organization organization) {
        String oldName = organizationMapper.getLeaderByname(organization.getName());
        adminMapper.updateRole(oldName, RoleConstant.PARTYMEMBER);
        String newName = organization.getLeader();
        int oid = organizationMapper.getIdByName(organization.getName());
        System.out.println(newName);
        PartyMember partyMember = adminMapper.getByName(newName);
        if (partyMember == null) {
            throw new AccountErrorException(MessageConstant.NAME_ERROR);
        }
        adminMapper.updateRole(newName, RoleConstant.ADMIN);
        organization.setId(oid);
        organization.setPId(partyMember.getId());
        log.info("organization {}", organization);
        organizationMapper.updatePartyOrg(organization);
    }

    @Override
    public List<Organization> getOrgName() {

        List<Organization> organizations = organizationMapper.getOrgName();
        return organizations;
    }
}
